package com.heima.health.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.health.mapper.OrderSettingMapper;
import com.heima.health.pojo.OrderSetting;
import com.heima.health.service.OrderSettingService;
import com.heima.health.utils.date.DateUtils;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class OrderSettingServiceImpl extends ServiceImpl<OrderSettingMapper, OrderSetting> implements OrderSettingService {
    @Override
    public boolean importOrderSettings(List<String[]> readExcel) {
        List<OrderSetting> orderSettings = changeStringToList(readExcel);
        for (OrderSetting orderSetting : orderSettings) {
            QueryWrapper<OrderSetting> wrapper = new QueryWrapper<>();
            wrapper.eq("ORDERDATE",orderSetting.getOrderDate());
            OrderSetting existOrNot = baseMapper.selectOne(wrapper);
            if (existOrNot!=null){
                orderSetting.setId(existOrNot.getId());
            }
        }
        return saveOrUpdateBatch(orderSettings, 100);
    }

    @Override
    public Map<String,OrderSetting> findSettingData(int year, int month) {
        String  beginDate = year+"-"+month+"-1";
        String  endDate = year+"-"+month+"-31";
        List<OrderSetting> orderSettingList = baseMapper.findSettingDataByOrderDate(beginDate, endDate);
        Map<String,OrderSetting> map=new HashMap<>();
        for (OrderSetting orderSetting : orderSettingList) {
            OrderSetting orderSetting1 = new OrderSetting();
            orderSetting1.setNumber(orderSetting.getNumber());
            orderSetting1.setReservations(orderSetting.getReservations());
            map.put(DateUtils.parseDate2String(orderSetting.getOrderDate(),"yyyy-MM-dd"),orderSetting1);
        }
        return map;
    }

    @Override
    public boolean updateNumberByOrderDate(int number, String orderdate) {
        return baseMapper.updateNumberByOrderDate(number, orderdate);
    }

    private List<OrderSetting> changeStringToList(List<String[]> readExcelList) {
        if(readExcelList!=null&&readExcelList.size()!=0){
            List<OrderSetting> list = new ArrayList<OrderSetting>();
            for (String[] strings : readExcelList) {
                OrderSetting orderSetting = new OrderSetting();
                orderSetting.setReservations(0);
                orderSetting.setNumber(Integer.parseInt(strings[1]));
                orderSetting.setOrderDate(DateUtils.parseString2Date(strings[0],"yyyy/MM/dd"));
                list.add(orderSetting);
            }
            return list;
        }
        return null;

    }
}
